<template>
  <el-dialog
  :before-close="handleClose"
    :title="dialogProps.title"
    :visible.sync="dialogProps.visible"
    width="560px"
    v-loading="loading"
  >
    <div slot="title" class="dialog-header">{{ dialogProps.title }}</div>
    <el-form :model="setmealModel"
      ref="userForm" label-width="80px" label-position="right" size="small">
      <el-tabs type="border-card" v-model="activeTabName" @tab-click="handleClick">
        <el-tab-pane name="setmealInfoTab" label="基本信息" class="user-info-tab-pane">
          <el-row>
            <el-col :span="12">
              <el-form-item label="编码">
                <el-input v-model="setmealModel.code"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="名称">
                <el-input v-model="setmealModel.name"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="适用性别">
                <el-select v-model="setmealModel.sex">
                  <el-option label="不限" value="0"></el-option>
                  <el-option label="男" value="1"></el-option>
                  <el-option label="女" value="2"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="助记码">
                <el-input v-model="setmealModel.helpCode"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="套餐价格">
                <el-input v-model="setmealModel.price"></el-input>
             </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="适用年龄">
                <el-input v-model="setmealModel.age"></el-input>
             </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="上传图片">
                <img height="178px" v-if="dialogImageUrl" class="avatar" :src="dialogImageUrl" >
                <el-upload
                  list-type="picture-card"
                  :http-request="ImgUploadSectionFile"
                  :auto-upload="autoUpload"
                  :before-upload="beforeAvatarUpload"
                  action="" 
                  ref="upload"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove">
                  <i class="el-icon-plus"></i>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible">
                  <img width="100%" :src="dialogImageUrl" alt="">
                </el-dialog>
             </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="说明">
                <el-input v-model="setmealModel.remark" type="textarea"></el-input>
             </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="注意事项">
                <el-input v-model="setmealModel.attention" type="textarea"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="检查组信息" name="second">
          <div class="checkScrol">
            <el-table
              limit=1
              height="239"
              ref="multipleTable"
              :data="checkgroupModel"
              @selection-change="handleSelectionChange"
              tooltip-effect="dark"
              style="width: 100%">
              <el-table-column
                type="selection"
                width="55">
              </el-table-column>
              <el-table-column
                prop="code"
                label="项目编码"
                width="120">
              </el-table-column>
              <el-table-column
                prop="name"
                label="项目名称"
                width="120">
              </el-table-column>
              <el-table-column
                prop="remark"
                label="项目说明"
                show-overflow-tooltip>
              </el-table-column>
            </el-table>
					</div>
        </el-tab-pane>
      </el-tabs>     
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="handleDialogClose()">取 消</el-button>
      <el-button type="primary" size="small" @click="submitForm('userForm')">确 定</el-button>
    </span>
    </el-tab-pane>
  </el-dialog>
</template>

<script>
import { upda, saveSetmeal, updateSetmeal } from '@/api/setmeal'
import { listAllCheckgroup } from "@/api/checkgroup";

export default {
  name: "setmeal-edit",
  data() {
    return {
      FileResult:{
        fileAddress:""
      },
      dialogImageUrl: '',
      autoUpload:true,//自动上传
      dialogVisible: false,
      activeTabName: "setmealInfoTab",
      loading: false,
      setmealModel: {
        img:"",
        checkGroups: {}
      },
      checkgroupModel: {},
      select: {},
      dialogProps: {
        visible: false,
        action: "",
        title: "",
      },
    };
  },
  methods: {
    ImgUploadSectionFile(param) {
      console.log(param);
      console.log(this.type);
      let formdata = new FormData();
      formdata.append("file", param.file);
      this.IconUpload(formdata);
    },
    async IconUpload(file) {
      const res = await upda(file);
      if(res.data.success==true){
        this.FileResult=res.data
        this.setmealModel.img="/static/"+res.data.message
      }
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //上传图片之前执行
    beforeAvatarUpload(file) {
      console.log("上传图片之前执行")
		  const isJPG = file.type === 'image/jpeg';
			const isLt2M = file.size / 1024 / 1024 < 2;
			if (!isJPG) {
				this.$message.error('上传套餐图片只能是 JPG 格式!');
			}
			if (!isLt2M) {
				this.$message.error('上传套餐图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    handleSelectionChange(val) {
      this.setmealModel.checkGroups = val;
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.dialogProps.action === "add") {
            this.doSaveSetmeal();
          } else {
            this.doUpdateSetmeal();
          }
        } else {
          return false;
        }
      });
    },
    doUpdateSetmeal() {
      updateSetmeal(this.setmealModel.id, this.setmealModel)
        .then((response) => {
          this.handleDialogClose();
          this.$emit("save-finished");
        })
        .catch((error) => {
          this.outputError(error);
        });
    },
    doSaveSetmeal() {
      saveSetmeal(this.setmealModel)
        .then((response) => {
          this.handleDialogClose();
          this.$emit("save-finished");
        })
        .catch((error) => {
          this.outputError(error);
        });
    },
    handleDialogClose() {
      this.dialogImageUrl= '',
      this.$refs.multipleTable.clearSelection();
      this.activeTabName = "setmealInfoTab";
      this.setmealModel = {};
      this.setmealModel.checkGroups = {};
      this.select = {};
      this.$refs.upload.clearFiles()
      this.dialogProps.visible = false;
    },
    handleClose(done) {
      this.handleDialogClose();
    },
    outputError(error) {
      console.log(error.response ? error.response : error.message);
      this.loading = false;
      this.$message({
        showClose: true,
        message: "出错了，请按F12查看浏览器日志。",
        type: "error",
      });
    },
    handleClick(tab, event) {
      if(this.select.length!=undefined){
        this.setmealModel.checkGroups = {};
        this.checkgroupModel.forEach((item,index) => {
          this.select.forEach(it => {
            if(item.id==it.id){
              this.$refs.multipleTable.toggleRowSelection(this.checkgroupModel[index]);
            }
          });
        });
      }
    }
  },
  mounted: function () {
    listAllCheckgroup()
      .then(response => {
        this.checkgroupModel = response.data;
      })
      .catch(error => {
        this.outputError(error)        
      })  
    this.$nextTick(() => {
      this.$on("openEditSetmealDialog", function (setmeal,checkgroup) {
        this.dialogImageUrl=setmeal.img;
        this.setmealModel = setmeal;
        this.setmealModel.checkGroups = checkgroup;
        this.dialogProps.action = "edit";
        this.dialogProps.title = "修改套餐";
        this.dialogProps.visible = true;
        this.select=checkgroup;
      });
      this.$on("openAddSetmealDialog", function () {
        this.dialogProps.action = "add";
        this.dialogProps.title = "添加套餐";
        this.setmealModel = {};
        this.setmealModel.checkGroups = {};
        this.select = {};
        this.dialogProps.visible = true;
      });
    });
  },
};
</script>

